<template>
  <div class="document-container">
    <tool-bar @searchFile="getByName" />
    <file-list :list="list" :nav="nav" @getFiles="getByType" />
  </div>
</template>

<script>
import toolBar from "@/components/Home/toolbar";
import fileList from "@/components/Home/list";
import { fileAPI } from "@/utils/api.js";
import { convert } from "@/utils/fileList.js";
import { mapState, mapMutations, mapGetters } from "vuex";
import Bus from "@/upload/bus.js";
export default {
  components: {
    toolBar,
    fileList
  },
  data() {
    return {
      list: [],
      nav: []
    };
  },
  computed: {
    ...mapGetters({
      root: "getRootId",
      type: "getClassifyType",
      isClassify: "getIsClassify"
    }),
    ...mapState({
      sort: state => state.files.sort
    })
  },
  watch: {
    /**
     * 监视sort改变
     */
    sort: {
      immediate: true,
      deep: true,
      handler(newSort) {
        this.list = this.sortList(this.list);
      }
    }
  },
  mounted() {
    if (!this.isClassify) return;
    this.getByType();
    Bus.$on("onAddFile", params => {
      fileAPI.common
        .add({
          fileType: "FILE",
          pathId: this.root,
          ...params
        })
        .then(res => {
          // 文件保存成功
          this.getByType();
          Bus.$emit("onGetUserSize");
          this.$message.success("文件保存成功");
        })
        .catch(err => {
          this.$message.error("文件保存失败");
        });
    });
  },
  methods: {
    /**
     * 获取分类文件
     */
    getByType() {
      fileAPI.operate
        .searchFile({
          leftSideType: this.type
        })
        .then(res => {
          this.nav = res.data.extras.path;
          this.list = this.sortList(res.data.rows);
        })
        .catch(err => {
          console.log(err);
        });
    },
    /**
     * 搜索文件
     */
    getByName(name) {
      fileAPI.operate
        .searchFile({
          leftSideType: this.type,
          name
        })
        .then(res => {
          this.nav = res.data.extras.path;
          this.list = this.sortList(res.data.rows);
        })
        .catch(err => {
          console.log(err);
        });
    },
    /**
     * 文件排序
     */
    sortList(list) {
      return convert(list, this.sort.attr, this.sort.order);
    }
  },
  destroyed() {
    Bus.$off("onAddFile");
  }
};
</script>

<style lang="scss" scoped>
</style>